using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.IO.Ports;

namespace blimp_compass
{

    class CompassSerial
    {
        static SerialPort ComPort;
        static ASCIIEncoding ASCIIEncoder = new ASCIIEncoding();

        //public static void OnSerialDataReceived(
        //object sender, SerialDataReceivedEventArgs args)
        //{
        //    string data = ComPort.ReadExisting();
            //Console.Write(data.Replace("\r", "\n"));
        //}

        bool CalibrationMode = false;
        
        public CompassSerial(string comPort)
        {
            string port = comPort;
            int baud = 9600;
            InitializeComPort(port, baud);
        }

        public void StartCalibration()
        {
            CalibrationMode = true;
            ComPort.Write("iC");
        }


        public void StopCalibration()
        {
            ComPort.Write("iE");
            CalibrationMode = false;
        }

        
        public double GetHeading()
        {
            if(CalibrationMode) return 0;

            ComPort.Write("h");

            ComPort.ReadTo(" Heading = \0");

            string l = ComPort.ReadLine();

            return Convert.ToInt32(l) / 10.0;
        }


       

        private void InitializeComPort(string port, int baud)
        {
            ComPort = new SerialPort(port, baud);
            ComPort.Parity = Parity.None;
            ComPort.StopBits = StopBits.One;
            ComPort.DataBits = 8;
            ComPort.Handshake = Handshake.None;
            //ComPort.DataReceived += OnSerialDataReceived;
            ComPort.ReadTimeout = 5000;
            ComPort.Open();
        }
    }

}
